import zipfile
import shutil, os, sys
from pathlib import Path
import datetime
import json

import  MyUtils

# -*- coding: utf-8 -*-
import cv2
import numpy as np
from PIL import ImageFont, Image, ImageDraw


def progress_bar(current, total, prefix='', suffix='', length=50, fill='='):
    """
    显示命令行进度条
    :param current: 当前进度
    :param total: 总进度
    :param prefix: 前缀文本
    :param suffix: 后缀文本
    :param length: 进度条长度
    :param fill: 填充字符
    """
    # 计算进度百分比
    percent = ("{0:.1f}").format(100 * (current / float(total)))
    
    # 计算填充长度
    filled_length = int(length * current // total)
    
    # 构建进度条
    bar = fill * filled_length + '>' * (1 if filled_length < length else 0) + ' ' * (length - filled_length)
    
    # 输出进度条（\r回到行首，不换行）
    sys.stdout.write(f'\r{prefix} |{bar}| {percent}% {suffix}')
    sys.stdout.flush()
    
    # 完成时换行
    if current == total:
        print()

#转换图像格式
def transformImageFormat(orgImgPath, dstImagePath, isNot):
    image = cvImread(orgImgPath)
    if image is None:
        return
    if isNot:
        image = cv2.bitwise_not(image)
    cvImwrite(dstImagePath, image)

def cvImread(path):
    image = cv2.imdecode(np.fromfile(path,dtype=np.uint8), -1)
    return image
def cvImwrite(path, image):
    split = os.path.splitext(path)
    fileFmt = split[-1]
    imgName = split[0]

    #compression_level = 9
    #params = [cv2.IMWRITE_PNG_COMPRESSION, compression_level]
    cv2.imencode(fileFmt, image)[1].tofile(path)

def transformImageFileFormat(orgImageDir, dstFormat, allowList,delOrgData):
    '''
    orgImageDir = "xxx/xxx/"
    dstFormat = ".jpg"
    allowList = [".jpg", ".png"]
    '''

    
        
    resultList = []
    pathList, wholePaths = MyUtils.recursive_listFiles(orgImageDir,True)
    total = len(pathList)
    for i in range(len(pathList)):
        # 更新进度条
        progress_bar(
            current=i,
            total=total,
            prefix='进度:',
            suffix=f'完成 {i}/{total}',
            length=30
        )

        srcFile = pathList[i]
        split = os.path.splitext(srcFile)
        fileFmt = split[-1]
        imgName = split[0]

        isOk = False
        for fmt in allowList:
            if fmt == fileFmt:
                isOk = True
        if not isOk:
            continue
        imagePath = wholePaths[i]
        imagePath2= os.path.splitext(imagePath)[0]+dstFormat
        transformImageFormat(imagePath, imagePath2,False)
        print("\n"+imagePath +" \ncvt into \n" + imagePath2)
        if delOrgData and os.path.exists(imagePath2):
            MyUtils.deleteFile(imagePath)
        resultList.append(imagePath)
        #print(imagePath)
    return  resultList
    
if __name__ == "__main__":

    path = "E:\\workspace\\0_model\\东莞-德普特手表模组\\"
    toFmt = ".png"
    resultList = transformImageFileFormat(path, toFmt,allowList=[".bmp"], delOrgData=True)
       
    l = len(resultList)
    i = 0
    for p in resultList:
        print(l,">>>",i, "transform: ", p)
        i += 1
    exit(0)
    #transformImageFormat()